package ServiceImpl;

import java.util.List;

import Bean.Car;
import Bean.User;
import Dao.CarDao;
import Dao.UserDao;
import Service.CarService;

public class CarServiceImpl implements CarService {

	@Override
	public boolean addCar(Car car)  {
		CarDao carDao = new CarDao();
		try {
			if(carDao.selectByCar_id(car.getCar_id()) == null) {
				carDao.insert(car);
				return true;
			} else {
				return false;
			}
		} catch(Exception e) {
			return false;
		}
	}

	@Override
	public boolean delectCar(Car car) {
		CarDao carDao = new CarDao();
		try {
			carDao.dropByCarId(car.getCar_id());
			return true;
		} catch(Exception e) {
			return false;
		}
	}

	@Override
	public Car selectCar(String car_id) {
		CarDao carDao = new CarDao();
		Car car = new Car();
		try {
			car = carDao.selectByCar_id(car_id);
		} catch(Exception e) {
			return null;
		}
		return car;
	}

	@Override
	public List<Car> selectAllCar() {
		CarDao carDao = new CarDao();
		try {
			return carDao.selectAllCar();
		} catch(Exception e) {
			return null;
		}
	}

	@Override
	public boolean saveAddCar(User user, Car car) {
		// 更加安全地添加车辆(确保车有车主)
		CarDao carDao = new CarDao();
		UserDao userDao = new UserDao();
		UserCarServiceImpl userCarServiceImpl = new UserCarServiceImpl();
		try {
			System.out.println("now search user is in list or not!");
			User tmpUser = userDao.selectByUsername(user.getUsername());
			System.out.println("now search car is in list or not!");
			Car tmpCar = carDao.selectByCar_id(car.getCar_id());
			System.out.println("user and car or searched!");
			if(tmpCar != null || tmpUser == null) {
				// 插入的车辆数据已存在或者用户数据不存在，均无法插入
				return false;
			} else {
				System.out.println("now ready to insert car!");
				carDao.insert(car);
				System.out.println("car inserted success!;");
				boolean isLinked = userCarServiceImpl.LinkCarToUser(user.getUsername(), car.getCar_id());
				System.out.println("car and user linked success!");
				// 验证车辆与车主的连接是否成功
				if(isLinked) {
					return true;
				} else {
					// 不成功则删除已插入car数据库的车辆信息，并返回false
					System.out.println("wrong, now delete car_id");
					carDao.dropByCarId(car.getCar_id());
					System.out.println("delete car success!");
					return false;
				}
			}
		} catch(Exception e) {
			System.out.println("exception!");
			return false;
		}

	}

	@Override
	public List<Car> selectCarByCreateTime(String createTime) {
		CarDao carDao = new CarDao();
		List<Car> cars = null; 
		try {
			cars = carDao.selectByCreateTime(createTime);
			return cars;
		} catch(Exception e) {
			return null;
		}
	}
}
